<template>
  <div class="bg-white rounded-lg shadow-md p-6">
    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
      <h2 class="text-xl font-semibold text-gray-800">我的评论</h2>
      <div class="flex flex-col sm:flex-row gap-2">
        <el-input
          v-model="searchQuery"
          placeholder="搜索评论内容"
          prefix-icon="Search"
          clearable
          @input="handleSearch"
          class="w-full sm:w-60"
        />
        <el-select 
          v-model="sortBy" 
          placeholder="排序方式" 
          @change="handleSort"
          class="w-full sm:w-32"
        >
          <el-option label="最新评论" value="newest" />
          <el-option label="最早评论" value="oldest" />
          <el-option label="文章标题" value="title" />
        </el-select>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="min-h-[400px]" v-loading="loading">
      <!-- 空状态 -->
      <el-empty
        v-if="!loading && commentsList.length === 0"
        description="暂无评论记录"
      >
        <template #image>
          <el-icon class="text-6xl text-gray-300"><ChatDotRound /></el-icon>
        </template>
        <el-button type="primary">浏览文章</el-button>
      </el-empty>

      <!-- 评论列表 -->
      <template v-else>
        <div class="mb-6">
          <el-table
            :data="commentsList"
            style="width: 100%"
            row-key="id"
            border
          >
            <!-- 文章标题 -->
            <el-table-column label="文章标题" min-width="200">
              <template #default="{ row }">
                <div class="truncate max-w-xs">
                  <el-link type="primary" underline="never">{{ row.articleTitle }}</el-link>
                </div>
              </template>
            </el-table-column>

            <!-- 评论内容 -->
            <el-table-column label="评论内容" min-width="300">
              <template #default="{ row }">
                <div class="text-gray-700 line-clamp-2">{{ row.content }}</div>
              </template>
            </el-table-column>

            <!-- 评论时间 -->
            <el-table-column label="评论时间" width="180">
              <template #default="{ row }">
                <div class="flex items-center text-gray-500 text-sm">
                  <el-icon class="mr-1"><Calendar /></el-icon>
                  <span>{{ formatDate(row.createdAt) }}</span>
                </div>
              </template>
            </el-table-column>

            <!-- 操作 -->
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <div class="flex justify-center">
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleDeleteComment(row.id)"
                    :loading="deletingId === row.id"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="mt-8 flex justify-center">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalItems"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
          />
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, ChatDotRound, Calendar } from '@element-plus/icons-vue'
import { useContentStore } from '../store'

const contentStore = useContentStore()

// 状态
const loading = ref(false)
const deletingId = ref(null)
const searchQuery = ref('')
const sortBy = ref('newest')
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)
const comments = ref([])

// 计算属性
const commentsList = computed(() => {
  let list = [...comments.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    list = list.filter(item => 
      item.content.toLowerCase().includes(query) || 
      item.articleTitle.toLowerCase().includes(query)
    )
  }
  
  // 排序
  switch (sortBy.value) {
    case 'newest':
      list.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
      break
    case 'oldest':
      list.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))
      break
    case 'title':
      list.sort((a, b) => a.articleTitle.localeCompare(b.articleTitle))
      break
  }
  
  return list
})

// 监听搜索和排序变化，重置页码
watch([searchQuery, sortBy], () => {
  currentPage.value = 1
})

// 初始化
onMounted(() => {
  loadComments()
})

// 加载评论列表
async function loadComments() {
  try {
    loading.value = true
    const result = await contentStore.getComments(currentPage.value, pageSize.value)
    comments.value = result.items
    totalItems.value = result.total
  } catch (error) {
    console.error('加载评论列表失败:', error)
    ElMessage.error('加载评论列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
function handleSearch() {
  // 搜索逻辑已在计算属性中实现
}

// 处理排序
function handleSort() {
  // 排序逻辑已在计算属性中实现
}

// 处理分页大小变化
function handleSizeChange(size) {
  pageSize.value = size
  loadComments()
}

// 处理页码变化
function handleCurrentChange(page) {
  currentPage.value = page
  loadComments()
}

// 删除评论
async function handleDeleteComment(id) {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条评论吗？',
      '删除评论',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    deletingId.value = id
    await contentStore.removeComment(id)
    comments.value = comments.value.filter(item => item.id !== id)
    totalItems.value--
    
    ElMessage.success('评论已删除')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error)
      ElMessage.error('删除评论失败')
    }
  } finally {
    deletingId.value = null
  }
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return ''
  
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return dateString
  }
}
</script>